//
//  ListSearchController
//  GroceryStoryboards
//
//  Created by jose on 10/03/13.
//  Copyright (c) 2013 Jose Luis Lopez. All rights reserved.
//

#import "ListSearchController.h"
#import "Constants.h"
#import "ManageController.h"

@interface ListSearchController ()

@end

@implementation ListSearchController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.screenName = @"List Screen";
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    
    editItem = nil;
    
    [self.tableView setContentOffset:CGPointMake(0, 44)];
    
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft:)];
    [swipeGesture setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [self.tableView addGestureRecognizer:swipeGesture];

    UISwipeGestureRecognizer *swipeGestureR = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)];
    [swipeGestureR setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [self.tableView addGestureRecognizer:swipeGestureR];

    self.isSearching = NO;
    
    [[[GAI sharedInstance] defaultTracker] send:
     [[GAIDictionaryBuilder createEventWithCategory:@"amount_items"
                                             action:@"button_press"
                                              label:[NSString stringWithFormat:@"%d", [[ItemsController getItems] count]]
                                              value:nil]
      build]];
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.arrayOriginal = [NSMutableArray arrayWithArray:[ItemsController getItems]];
    self.arrayGroceries = [NSMutableArray arrayWithArray:self.arrayOriginal];
    
    [self.tableView reloadData];
    

}

#pragma mark - Table View

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.isSearching = NO;
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    [self.textField resignFirstResponder];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0)
        if (self.isSearching)
            return 0;
        else
            return 1;
    else if (section == 1)
        return 1;
    else {
        
        NSInteger numRows = [self.arrayGroceries count];
        if (numRows > 0) {

            [self.emptyTextView setAlpha:0];
            [self.tableView setScrollEnabled:YES];
        } else {
            [UIView animateWithDuration:0.5 animations:^() {
            
                if (!self.isSearching)
                    [self.emptyTextView setAlpha:1];
            }];
            
            
            [self.tableView setScrollEnabled:NO];
        }
        
        return numRows;
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *cellIdentifier;
    if (indexPath.section == 0) cellIdentifier = @"AddGroceryCellIdentifier";
    else if (indexPath.section == 1) cellIdentifier = @"SearchCellIdentifier";
    else cellIdentifier = @"NormalCellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    
    if (indexPath.section == 0){
        if (!self.isSearching) {

//            [((UIButton *)[cell viewWithTag:1]).titleLabel setText:@"OPTIONS"];
            [((UIButton *)[cell viewWithTag:1]) addTarget:self action:@selector(settingsPressed) forControlEvents:UIControlEventTouchUpInside];
//            [((UIButton *)[cell viewWithTag:2]).titleLabel setText:@"ADD ITEM"];
            [((UIButton *)[cell viewWithTag:2]) addTarget:self action:@selector(addGroceryPressed) forControlEvents:UIControlEventTouchUpInside];
        }
    } else if (indexPath.section == 1) {
        
        self.textField = (UITextField *) [cell viewWithTag:1];
        
    } else {
                
//        NSDictionary *dictGrocery = [self.arrayGroceries objectAtIndex:indexPath.row];
//        [((UILabel *) [cell viewWithTag:1]) setText:[dictGrocery valueForKey:@"name"]];
//        [((UILabel *) [cell viewWithTag:1]) setTextColor:[UIColor blackColor]];
//        [((UILabel *) [cell viewWithTag:2]) setText:[NSString stringWithFormat:@"%@ %@", [dictGrocery valueForKey:@"ammount"], [dictGrocery valueForKey:@"unity"]]];
//        [((UILabel *) [cell viewWithTag:3]) setText:[NSString stringWithFormat:@"%@ %@", [dictGrocery valueForKey:@"price"], [[NSUserDefaults standardUserDefaults] valueForKey:kCurrencyKey]]];

        Item *item = [self.arrayGroceries objectAtIndex:indexPath.row];
        [((UILabel *) [cell viewWithTag:1]) setText:item.itemName];
        [((UILabel *) [cell viewWithTag:1]) setTextColor:[UIColor darkGrayColor]];
        [((UILabel *) [cell viewWithTag:2]) setText:[NSString stringWithFormat:@"%@ %@", item.itemQuantity, item.itemUnity]];
        if ([item.itemPrice length] > 0)
            [((UILabel *) [cell viewWithTag:3]) setText:[NSString stringWithFormat:@"%@ %@", item.itemPrice, [[NSUserDefaults standardUserDefaults] valueForKey:kCurrencyKey]]];
        else
            [((UILabel *) [cell viewWithTag:3]) setText:@""];

        [[cell viewWithTag:4] setFrame:CGRectMake(320, 0, 0, 44)];
        [[cell viewWithTag:5] setHidden:YES];
        [((UIButton *)[cell viewWithTag:5]) addTarget:self action:@selector(editRow:) forControlEvents:UIControlEventTouchUpInside];
        [[cell viewWithTag:6] setHidden:YES];
        [((UIButton *)[cell viewWithTag:6]) addTarget:self action:@selector(deleteRow:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - Swipe gesture

-(void)swipeLeft:(UISwipeGestureRecognizer *)gesture {

    CGPoint swipeLocation = [gesture locationInView:self.tableView];
    NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:swipeLocation];
    
    if (swipedIndexPath.section == 2) {
     
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
        
        [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^(void) {
            
            UIView *view = [cell viewWithTag:4];
            view.frame = CGRectMake(0, 0, 320, 44);
            
        }completion:^(BOOL res) {
            
            UILabel *label = (UILabel *)[cell viewWithTag:1];
            [[cell contentView] bringSubviewToFront:label];
            [label setFrame:CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width - 38, label.frame.size.height)];
            [label setTextColor:[UIColor whiteColor]];
            [cell setNeedsDisplay];
            
            // No edit for now
            [[cell contentView] bringSubviewToFront:[cell viewWithTag:5]];
            [[cell viewWithTag:5] setHidden:NO];
            [[cell contentView] bringSubviewToFront:[cell viewWithTag:6]];
            [[cell viewWithTag:6] setHidden:NO];
        }];
    }
}

-(void)swipeRight:(UISwipeGestureRecognizer*)gesture {
    
    CGPoint swipeLocation = [gesture locationInView:self.tableView];
    NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:swipeLocation];
    if (swipedIndexPath.section == 2) {
        
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
        
        UIView *view = [cell viewWithTag:4];
        [cell.contentView bringSubviewToFront:view];
        
        UILabel *label = (UILabel *)[cell viewWithTag:1];
        [label setTextColor:[UIColor darkGrayColor]];
        [label setFrame:CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width + 38, label.frame.size.height)];
        
        // No edit for now
        [[cell viewWithTag:5] setHidden:YES];
        [[cell viewWithTag:6] setHidden:YES];
        
        [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^(void) {
            
            UIView *view = [cell viewWithTag:4];
            view.frame = CGRectMake(320, 0, 0, 44);
            
        }completion:^(BOOL res) {
            
        }];
    }
}

#pragma mark - Cell buttons

-(void)deleteRow:(UIButton *)sender {
    
    
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil) {
        
        // Remove it from the database
        [ItemsController deleteItem:[self.arrayOriginal objectAtIndex:indexPath.row]];
        // Remove it from the data source
        [self.arrayOriginal removeObjectAtIndex:indexPath.row];
        self.arrayGroceries = [NSMutableArray arrayWithArray:self.arrayOriginal];
        // Delete it from the tableView
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

-(void)editRow:(UIButton *)sender {
    
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil) {
        editItem = [self.arrayGroceries objectAtIndex:indexPath.row];
        [self performSegueWithIdentifier:@"ManageSegue" sender:self];
    }
}

#pragma mark - Text Field

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    self.isSearching = YES;
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    return YES;
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    
    NSString *searchString = textField.text;
    if ([string length] == 0)
        searchString = [searchString substringToIndex:([searchString length] - 1)];
    
    searchString = [[[[[NSString stringWithFormat:@"%@%@", searchString, string]
                              stringByReplacingOccurrencesOfString:@"\n" withString:@""]
                              stringByReplacingOccurrencesOfString:@"\t" withString:@""]
                              stringByReplacingOccurrencesOfString:@"\r" withString:@""]
                                  stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    
    if ([searchString length] == 0)
        self.arrayGroceries = [NSMutableArray arrayWithArray:self.arrayOriginal];
    else {
        
        NSMutableArray *filteredArray = [[NSMutableArray alloc] init];
     
        for (int i = 0; i < [self.arrayOriginal count]; i ++) {
            
//            NSDictionary *grocery = [self.arrayOriginal objectAtIndex:i];
//            if ([[[grocery valueForKey:@"name"] lowercaseString] rangeOfString:[searchString lowercaseString]].location != NSNotFound) {
//                [filteredArray addObject:grocery];
//            }
            
            Item *item = [self.arrayOriginal objectAtIndex:i];
            if ([[item.itemName lowercaseString] rangeOfString:[searchString lowercaseString]].location != NSNotFound) {
                [filteredArray addObject:item];
            }
        }
        
        self.arrayGroceries = [NSMutableArray arrayWithArray:filteredArray];

    }
    
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade];

    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    self.isSearching = NO;
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Settings and Add grocery button

-(void)settingsPressed {

    [self performSegueWithIdentifier:@"SettingsSegue" sender:self];
}

-(void)addGroceryPressed {
    
    [self performSegueWithIdentifier:@"ManageSegue" sender:self];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

//    ((UIViewController *)segue.destinationViewController).view.frame = CGRectMake(320, 0, 320, 480);
//    
//    [UIView animateWithDuration:0.5 animations:^(void) {
//        
//        ((UIViewController *)segue.destinationViewController).view.frame = CGRectMake(0, 0, 320, 480);
//    }];
    if ([segue.identifier isEqualToString:@"ManageSegue"] && editItem != nil) {
        ((ManageController *)segue.destinationViewController).item = editItem;
        editItem = nil;
    }
}

@end
